/**
 *
 */
package com.handinfo.uimenu.window;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Graphics;

import lib.jf.SMSSender;
import lib.jf.SMSSender.SMSCallBack;

import org.apache.http.client.HttpClient;

import android.util.Log;

import com.handinfo.engine.AbstractGameScreen;
import com.handinfo.engine.GameMIDlet;
import com.handinfo.engine.GameManager;
import com.handinfo.engine.net.GameProtocol;
import com.handinfo.game.ActorRole;
import com.handinfo.game.GameMessage;
import com.handinfo.game.UserScreen;
import com.handinfo.uimenu.AbsHyperLinker;
import com.handinfo.uimenu.UIAbstractWindow;
import com.handinfo.uimenu.UIListener;
import com.handinfo.uimenu.UIManager;
import com.handinfo.uimenu.UIMessageBox;
import com.handinfo.uimenu.UITools;
import com.handinfo.uimenu.UIWindowFactory;
import com.handinfo.util.Tools;
import com.test.touch.GameTouchManager;
import com.xl.lib.Utils;

/**
 * 多币种购买道具，任务，功能等
 *
 * @author venizeng
 *
 */
public class UIMultiMoney extends UIAbstractWindow {
	private final int STATE_TASK_IM_BUY = 1;// 立即购买
	private final int STATE_TASK_IM_FIN = 2;// 立即完成
	private final int STATE_ITEM = 3;// 购买道具
	private final int STATE_ITEM_BUYING = 7;// 购买道具
	private final int STATE_ITEM_SUC = 4;// 购买道具
	private final int STATE_ITEM_FAILED = 5;// 购买道具
	private final int STATE_PRESENT = 4;// 赠送道具
	private final int STATE_BUY_FUN = 5;// 消耗金钱做某事
	//
	private final int INDEX_NUM = 1;
	private final int INDEX_YINPIAO = 2;
	private final int INDEX_RMB = 3;

	private String m_title;
	private int m_num = 1;
	private int m_num_max;
	private long m_price_yinpiao;
	private long m_price_rmb;
	//
	private Object m_describe;
	private int m_h_descrbei;
	// logic
	private boolean m_is_selYinpiao;// 是否选中的是银票
	// item
	private String m_item_name;
	private String m_item_key;
	// present
	private String m_name_recver;
	private long m_id_recver;
	// task
	private String m_task_id;
	private String m_task_name;
	// money
	private int m_oper_type_buy_fun;// 标示操作

	/**
	 * @param id
	 */
	public UIMultiMoney(int id) {
		super(id);
	}



	protected void registerTouch() {
		clearAllRects();
		registerNormalSoft();
		int[][] rect = new int[][]{
				{369,132,36,22},
				{424,132,36,22},
				{384,158,30,24},
				{414,158,30,24},
		};
		initTouchRect(rect);
	}



	protected void onTouchRect(int[][] rect, int touchid) {
		switch(touchid) {
		case 0:
			GameTouchManager.keyPressedDir(0);
			break;
		case 1:
			GameTouchManager.keyPressedDir(1);
			break;
		case 2:
			m_index = INDEX_YINPIAO;
			m_is_selYinpiao = true;
		case 3:
			m_index = INDEX_RMB;
			m_is_selYinpiao = false;
			break;
		}
	}



	/**
	 * 2012-5-3 下午06:34:14 venizeng
	 *
	 * @param csOpenMarket
	 * @param dis
	 * @throws IOException
	 */
	public static void recvMessage(int order, DataInputStream dis) throws IOException {
		switch (order) {
	    case GameProtocol.S_RMB_GET_ITEM_DOWN:
	        byte state = dis.readByte();
	        m_getitem_suc = (state == 1);
	        break;
		case GameProtocol.CS_BUY_ITEM_WITH_MUL_MONEY:
		case GameProtocol.CS_PRESENT_ITEM_WITH_MUL_MONEY:
		case GameProtocol.CS_BUY_FUN_WITH_MUL_MONEY:
			state = dis.readByte();
			String info = dis.readUTF();
			if (!info.equals("")) {
				GameManager.getInstance().addSystemInfo(GameManager.SYSTEM_INFO_TYPE_B, info);
			}
			if (state == 0) {// 失败继续
				return;
			}
			UIMultiMoney market2 = (UIMultiMoney) UIManager.getInstance().getWindowById(UIWindowFactory.WINDOW_MULTIMONEY);
			if (market2 == null) {
				return;
			}
			market2.close();
			break;
		case GameProtocol.S_ACTORITEM_BUY_ALERT:
			String key = dis.readUTF();
			String name = dis.readUTF();
			long price_yinpiao = dis.readLong();
			long price_rmb = dis.readLong();
//			UIMultiMoney.gotoBuyItem(name, key, price_yinpiao, price_rmb);//谢亮去掉。
			break;

		}
	}

	/**
	 * 多币种购买道具入口 2012-4-25 上午09:38:03 venizeng
	 *
	 * @param name
	 * @param id
	 * @param price_yinpiao
	 * @param price_rmb
	 */
	public static void gotoBuyItem(String name, String key, long price_yinpiao, long price_rmb) {
		UIMultiMoney market2 = (UIMultiMoney) UIWindowFactory.createWindow(UIWindowFactory.WINDOW_MULTIMONEY);
		int X_SEND = 20;// 相对list界面的宽度
		int Y_SEND = 30;
		market2.setBounds(UITools.X_BG + X_SEND, UITools.Y_BG + Y_SEND, UITools.W_BG - (X_SEND << 1), UITools.H_BG - (Y_SEND << 1));
		market2.setCommonData("购买道具", 999, price_yinpiao, price_rmb);
		//
		market2.m_item_name = name;
		market2.m_item_key = key;
		//
		market2.setWindowStatus(market2.STATE_ITEM);
		market2.setCommonIndex();
		UIManager.getInstance().addWindow(market2);
	}

	public static void gotoPresent(String name, String itemKey, long price_yinpiao, long price_rmb, long id, String name_recver) {
		UIMultiMoney market2 = (UIMultiMoney) UIWindowFactory.createWindow(UIWindowFactory.WINDOW_MULTIMONEY);
		int X_SEND = 20;// 相对list界面的宽度
		int Y_SEND = 20;
		market2.setBounds(UITools.X_BG + X_SEND, UITools.X_BG + Y_SEND, UITools.W_BG - (X_SEND << 1), UITools.H_BG - (Y_SEND << 1));
		market2.setCommonData("赠送道具", 999, price_yinpiao, price_rmb);
		//
		market2.m_item_name = name;
		market2.m_item_key = itemKey;
		market2.m_id_recver = id;
		market2.m_name_recver = name_recver;
		//
		market2.setWindowStatus(market2.STATE_PRESENT);
		market2.setCommonIndex();
		UIManager.getInstance().addWindow(market2);
	}

	/**
	 * 立即购买 2012-4-24 下午01:38:58 venizeng
	 *
	 * @param name_title
	 *            标题
	 * @param id_task
	 *            任务的Id
	 * @param num_max
	 *            购买的最大数目限制，如果无则为0
	 * @param describe
	 *            任务的描述，如涉及到文字中有变量需特殊显示，则将需要特殊显示的部分用<mark c=898098>颜色</mark>进行定义
	 * @param price_yinpiao
	 *            购买任务的银票单价，如不支持为0
	 * @param price_rmb
	 *            购买任务的元宝单价，如不支持为0
	 */
	public static void gotoBuyTaskImBuy(String name_title, String name_task, String id_task, int num_max, String describe, long price_yinpiao, long price_rmb) {
		UIMultiMoney market2 = (UIMultiMoney) UIWindowFactory.createWindow(UIWindowFactory.WINDOW_MULTIMONEY);
		market2.gotoTask(name_title, name_task, id_task, num_max, describe, price_yinpiao, price_rmb, market2.STATE_TASK_IM_BUY);
		UIManager.getInstance().addWindow(market2);
	}

	/**
	 * 立即完成 2012-4-25 上午10:40:55 venizeng
	 *
	 * @param name_title
	 * @param id_task
	 * @param num_max
	 * @param describe
	 * @param price_yinpiao
	 * @param price_rmb
	 */
	public static void gotoBuyTaskImFin(String name_title, String name_task, String id_task, int num_max, String describe, long price_yinpiao, long price_rmb) {
		UIMultiMoney market2 = (UIMultiMoney) UIWindowFactory.createWindow(UIWindowFactory.WINDOW_MULTIMONEY);
		market2.gotoTask(name_title, name_task, id_task, num_max, describe, price_yinpiao, price_rmb, market2.STATE_TASK_IM_FIN);
		UIManager.getInstance().addWindow(market2);
	}

	private void gotoTask(String name_title, String name_task, String id_task, int num_max, String describe, long price_yinpiao, long price_rmb, int state) {
		int X_SEND = 20;// 相对list界面的宽度
		int Y_SEND = num_max == 0 ? 30 : 10;
		setBounds(UITools.X_BG + X_SEND, UITools.Y_BG + Y_SEND, UITools.W_BG - (X_SEND << 1), UITools.H_BG - (Y_SEND << 1));
		// 通用数据
		setCommonData(name_title, num_max, price_yinpiao, price_rmb);
		// 特殊数据
		if (AbsHyperLinker.isHyperLink(describe)) {
			AbsHyperLinker hyperLinker = AbsHyperLinker.createHyperLinker(describe, m_w - (UITools.INITX_CONTENT << 1), 100);
			m_h_descrbei = hyperLinker.getRealHeight();
			hyperLinker.setH(m_h_descrbei);
			m_describe = hyperLinker;
		} else {
			m_describe = Tools.getStrArray(describe, m_w - (UITools.INITX_CONTENT << 1));
		}
		m_task_id = id_task;
		m_task_name = name_task;
		//
		setWindowStatus(state);
		setCommonIndex();
	}

	private byte m_dongfu_type;

	public static void gotoBuyJiasuWithMoney(String name_title, String name_describe, long price_yinpiao, long price_rmb, byte type) {
		UIMultiMoney market2 = (UIMultiMoney) UIWindowFactory.createWindow(UIWindowFactory.WINDOW_MULTIMONEY);
		market2.gotoBuySthWithMoney(name_title, 1, name_describe, price_yinpiao, price_rmb, market2.STATE_BUY_FUN, 1);
		market2.m_dongfu_type = type;
		UIManager.getInstance().addWindow(market2);
	}

	private void gotoBuySthWithMoney(String name_title, int num_max, String describe, long price_yinpiao, long price_rmb, int state, int operType) {
		int X_SEND = 20;// 相对list界面的宽度
		int Y_SEND = num_max == 0 ? 30 : 10;
		setBounds(UITools.X_BG + X_SEND, UITools.Y_BG + Y_SEND, UITools.W_BG - (X_SEND << 1), UITools.H_BG - (Y_SEND << 1));
		// 通用数据
		setCommonData(name_title, num_max, price_yinpiao, price_rmb);
		// 特殊数据
		// m_describe = AbsHyperLinker.createHyperLinker(describe, m_w -
		// (UITools.INITX_CONTENT << 1), 100);
		// m_h_descrbei = m_describe.getRealHeight();
		// m_describe.setH(m_h_descrbei);

		if (AbsHyperLinker.isHyperLink(describe)) {
			AbsHyperLinker hyperLinker = AbsHyperLinker.createHyperLinker(describe, m_w - (UITools.INITX_CONTENT << 1), 100);
			m_h_descrbei = hyperLinker.getRealHeight();
			hyperLinker.setH(m_h_descrbei);
			m_describe = hyperLinker;
		} else {
			m_describe = Tools.getStrArray(describe, m_w - (UITools.INITX_CONTENT << 1));
		}

		m_oper_type_buy_fun = operType;
		//
		setWindowStatus(state);
		setCommonIndex();
	}

	private void setCommonData(String name_title, int num_max, long price_yinpiao, long price_rmb) {
		m_price_yinpiao = price_yinpiao;
		m_price_rmb = price_rmb;
		m_num_max = num_max;
		m_title = name_title;
	}

	private void setCommonIndex() {
		if (m_num_max != 0) {
			setBuyIndex(INDEX_NUM);
		} else {
			if (isSupportYinpiao()) {
				setBuyIndex(INDEX_YINPIAO);
			} else {
				setBuyIndex(INDEX_RMB);
			}
		}
	}
	public static byte[] getByteFromInputstream(DataInputStream dis) {
	    ByteArrayOutputStream aos = new ByteArrayOutputStream();
        byte[] buffer = new byte[2048];
        int read = 0;
        byte[] data = null;
        try {
            while((read=dis.read(buffer)) > 0) {
                aos.write(buffer, 0, read);
            }
            data = aos.toByteArray();
            aos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return data;
	}

//	000073209001   延命散
//	000073209002    招魂灵牌
//	000073209003    太虚灵丹
//	000073209004    双倍经验卡
//	000073209005    仇恨之心
//	000073209006    赤诚之心
//	000073209007    愤怒之心
//	000073209008    感激之心
//	000073209009    招财令
//	000073209010    续命包
	public static String[] consumecodes= new String[]{
	    "000073209009",//招财令
	    "000073209010",//续命包
	    "000073209003",//太虚灵丹
	    "000073209006",//赤诚之心
	    "000073209007",//  愤怒之心
	    "000073209008",//感激之心
	    "000073209005",//仇恨之心
	    "000073209002",//招魂灵牌
	    "000073209001",//延命散
	    "000073209004",//双倍经验卡
	};

	private static final String FeeType = "12";
	private static final String CPID = "741004";
	private static final String CPServiceID = "600410073210";
	private static final String ConsumeCode = "0000732090";//"0000540990";//000054099001
	private static final String FID = "1000";
	private static final String PackageID = "000000000000";
	private static final String CPSign = "000000";
	private static String CPParam = "";
	private String debug_string = "";
	private static boolean m_sms_suc = false;
	private static boolean m_getitem_suc = false;
	private Runnable mbuying = new Runnable() {
        @Override
        public void run() {
            try {
                m_sms_suc = false;
                m_getitem_suc = false;
                /////////////////////////获取id/////////////////////////////////////////////
//                String id="";
                // 获取ID
                debug_string = "\n正在获取id";
                SimpleDateFormat dateformat1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String a1=dateformat1.format(new Date()).replace(" ", "%20");
                String s = "http://58.215.185.99:18001/DTgame_HTTP/http_notifyBilling?ga.field=0,&,#,$";
                s = s.replace("#", Long.toString(GameManager.getInstance().m_role.m_gameID));
                s = s.replace("&", UserScreen.m_login_name);
                s = s.replace("$", a1);
                Log.d("xltest", "url="+s);
                try {
                    HttpConnection http = (HttpConnection)Connector.open(s);
                    DataInputStream dis = http.openDataInputStream();
                    byte[] array = getByteFromInputstream(dis);
                    String result = new String(array);
                    Log.d("xltest", "get id result is ="+result);
                    String[] as = result.split(",");
                    if (as.length == 2 && as[0].equals("10000")) {
                        Log.d("xltest", "get id sucess ,id="+as[1]);
                        CPParam = as[1].trim();
                    }
                    http.close();
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (CPParam.equals("")) {
                    Log.d("xltest", "get id failed!");
                    setWindowStatus(STATE_ITEM_FAILED);
                    return;
                }
                Thread.sleep(1000);
///////////////////////////////////发生短信/////////////////////////////////////////
                // 发送短信
                debug_string = "\n正在发生短信";
                String adress = "106588992";
                StringBuffer sb = new StringBuffer();
                sb.append(FeeType);
                sb.append(CPID);
                sb.append(CPServiceID);
                sb.append(ConsumeCode);
                sb.append(consumecodes[m_curbuyindex]);
//                if(m_curbuyindex < 10) {
//                    sb.append("0");
//                    sb.append(m_curbuyindex);
//                } else {
//                    sb.append(m_curbuyindex);
//                }
                sb.append(FID);
                sb.append(PackageID);
                sb.append(CPSign);
                sb.append(CPParam);
                Log.d("xltest", "content="+sb.toString());
                SMSSender.sendSMS(Utils.getContext(), adress, sb.toString().trim(), new SMSCallBack() {
//                    SMSSender.sendSMS(Utils.getContext(), "10086", "CXYE", new SMSCallBack() {
                    @Override
                    public void success() {
                        m_sms_suc = true;
                    }
                });
                int sleep_count = 0;
                while(!m_sms_suc) {
                    if (sleep_count > 8) {
                        break;
                    }
                    Thread.sleep(5000);
                    sleep_count ++;
                }

                if (!m_sms_suc) {
                    Log.d("xltest", "send sms failed!");
                    setWindowStatus(STATE_ITEM_FAILED);
                    return;
                }
                /////////////////////////////验证购买//////////////////////////////////////
             // 验证购买
                debug_string = "\n正在验证购买";
                s = "http://58.215.185.99:18001/DTgame_HTTP/http_polling?id="+CPParam.trim();
                boolean buyed = false;
                try {
                    HttpConnection http = (HttpConnection)Connector.open(s);
                    DataInputStream dis = http.openDataInputStream();
                    byte[] array = getByteFromInputstream(dis);
                    String result = new String(array);
                    buyed = result.contains("10000");
                    http.close();
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (!buyed) {
                    Log.d("xltest", "check buyed failed!");
                    setWindowStatus(STATE_ITEM_FAILED);
                    return;
                }
                Thread.sleep(1000);
                ////////////////////////添加物品/////////////////////////
                // 添加物品
                debug_string = "\n正在添加物品";

                GameManager.getInstance().m_game_message.sendGetBuyItemInMulMoney(m_item_key, GameManager.getInstance().m_role.m_gameID);

                sleep_count = 0;
                while(!m_getitem_suc) {
                    if (sleep_count > 13) {
                        break;
                    }
                    Thread.sleep(3000);
                    sleep_count ++;
                }
                if (m_getitem_suc) {
                    setWindowStatus(STATE_ITEM_SUC);
                } else {
                    setWindowStatus(STATE_ITEM_FAILED);
                    GameManager.getInstance().m_game_message.unlockNetwork();
                }
                Log.d("xltest", "get item "+(m_getitem_suc?"suc":"failed"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
	private long m_buyStartTime;
	private static int m_curbuyindex;
	public static void setBuyedIndex(int index) {
	    Log.d("xltest", "current index="+index);
	    m_curbuyindex = index;
	}
	protected void keyLogic() {
        switch (m_state) {
            case STATE_ITEM:
//                String toDraw = STR_BUY_YD.replace("#", m_item_name);
                if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT) || AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
//                    actionLeftSoft();
                    m_buyStartTime = System.currentTimeMillis();
                    new Thread(mbuying).start();
                    setWindowStatus(STATE_ITEM_BUYING);
                } else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT_SOFT)) {
                    close();
                }
                break;
            case STATE_ITEM_SUC:
                if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT) || AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
                    close();
                } else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT_SOFT)) {
                    close();
                }
                break;
            case STATE_ITEM_FAILED:
                if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT) || AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
                    close();
                } else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT_SOFT)) {
                    close();
                }
                break;
            case STATE_ITEM_BUYING:
                if (System.currentTimeMillis() - m_buyStartTime > 80000) {
                    setWindowStatus(STATE_ITEM_FAILED);
                }
                break;
        }
//		if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT) || AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
//			actionLeftSoft();
//		} else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT_SOFT)) {
//			close();
//		} else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_UP)) {
//			dirUpDown();
//		} else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_DOWN)) {
//			dirUpDown();
//		} else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT) || AbstractGameScreen.haveKeyHold(AbstractGameScreen.GK_LEFT)) {
//			if (m_index == INDEX_NUM) {
//				if (m_num_max <= 0) {
//					return;
//				}
//				if (m_num <= 1) {
//					changeNum(999);
//				} else {
//					changeNum(m_num - 1);
//				}
//			} else {
//				dirLeftRight();
//			}
//		} else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT) || AbstractGameScreen.haveKeyHold(AbstractGameScreen.GK_RIGHT)) {
//			if (m_index == INDEX_NUM) {
//				if (m_num_max == 0) {
//					return;
//				}
//				if (m_num >= m_num_max) {
//					changeNum(1);
//				} else {
//					changeNum(m_num + 1);
//				}
//			} else {
//				dirLeftRight();
//			}
//		}
	}

	private void dirUpDown() {
		switch (m_index) {
		case INDEX_NUM:
			if (isSupportYinpiao()) {
				setBuyIndex(INDEX_YINPIAO);
			} else {
				setBuyIndex(INDEX_RMB);
			}
			break;
		case INDEX_YINPIAO:
		case INDEX_RMB:
		default:
			if (isSupportNum()) {
				setBuyIndex(INDEX_NUM);
			}
			break;
		}
	}

	private void dirLeftRight() {
		switch (m_index) {
		case INDEX_YINPIAO:
			setBuyIndex(INDEX_RMB);
			break;
		case INDEX_RMB:
			if (isSupportYinpiao()) {// 不支持银票
				setBuyIndex(INDEX_YINPIAO);
			}
			break;
		}
	}

	/**
	 * 设置谁获得焦点 2012-4-24 下午06:48:41 venizeng
	 *
	 * @param iNDEXRMB
	 */
	private void setBuyIndex(int index_buy) {
		m_index = index_buy;
		switch (m_index) {
		case INDEX_NUM:
			break;
		case INDEX_YINPIAO:
			m_is_selYinpiao = true;
			break;
		case INDEX_RMB:
			m_is_selYinpiao = false;
			break;
		}
	}

	/**
	 * 2012-4-24 下午06:54:20 venizeng
	 *
	 * @param i
	 */
	private void changeNum(int num) {
		m_num = num;
	}

	private boolean isSupportYinpiao() {
		return m_price_yinpiao != 0;
	}

	private boolean isSupportNum() {
		return m_num_max != 0;
	}

	private long getSumMoney() {
		if (m_is_selYinpiao) {
			return m_num * m_price_yinpiao;
		} else {
			return m_num * m_price_rmb;
		}
	}

	private boolean isMoneyEnough() {
		if (m_is_selYinpiao) {
			return GameManager.getInstance().m_role.m_money_yinpiao >= getSumMoney();
		} else {
			return GameManager.getInstance().m_role.m_money_rmb >= getSumMoney();
		}
	}

	private void actionLeftSoft() {
		if (isMoneyEnough()) {// 金钱足够
			final UIMessageBox messageBox = (UIMessageBox) UIManager.getInstance().createWindow(UIWindowFactory.WINDOW_MESSAGEBOX);
			messageBox.setMessage(getLeftSoftAlertStr());
			messageBox.addListener(new UIListener() {

				public void actionPerformed() {
					if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT) || AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
						switch (m_state) {
						case STATE_ITEM:
							actionLeftSoftOnBuyItem();
							break;
						case STATE_PRESENT:
							actionLeftSoftOnPresentItem();
							break;
						case STATE_TASK_IM_BUY:
							actionLeftSoftOnTaskImBuy();
							break;
						case STATE_TASK_IM_FIN:
							actionLeftSoftOnTaskImFin();
							break;
						case STATE_BUY_FUN:
							actionLeftSoftOnBuyFunWithMoney();
							break;
						}
						close();
						UIManager.getInstance().removeWindow(messageBox);
					} else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT_SOFT)) {
						UIManager.getInstance().removeWindow(messageBox);
					}
				}
			});
		} else {
			final UIMessageBox messageBox = (UIMessageBox) UIManager.getInstance().createWindow(UIWindowFactory.WINDOW_MESSAGEBOX);
			String temp = m_is_selYinpiao ? "银票不足，您可以充值元宝进行消费" : "元宝不足，请您先进行充值";
			messageBox.setMessage(temp);
			messageBox.addListener(new UIListener() {

				public void actionPerformed() {
					if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT) || AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
						UIChongzhi.gotoChongzhi();
						UIManager.getInstance().removeWindow(messageBox);
					} else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT_SOFT)) {
						UIManager.getInstance().removeWindow(messageBox);
					}
				}
			});
		}
	}

	private String getLeftSoftAlertStr() {
		final int COLOR_NUM = Tools.GREEN;
		final int COLOR_NAME = Tools.RED;
		String temp = m_is_selYinpiao ? "银票" : "元宝";

		switch (m_state) {
		case STATE_ITEM:
			return "购买" + "<mark c=" + COLOR_NUM + ">" + m_num + "</mark>" + "个" + "<mark c=" + COLOR_NAME + ">" + m_item_name + "</mark>" + "将消耗" + "<mark c=" + COLOR_NUM + ">"
					+ getSumMoney() + "</mark>" + temp;
		case STATE_PRESENT:
			return "购买" + "<mark c=" + COLOR_NUM + ">" + m_num + "个" + "</mark>" + "<mark c=" + COLOR_NAME + ">" + m_item_name + "</mark>" + "并赠送给" + "<mark c=" + COLOR_NAME + ">"
					+ m_name_recver + "</mark>" + "将消耗" + "<mark c=" + COLOR_NUM + ">" + getSumMoney() + "</mark>" + temp;

		case STATE_TASK_IM_BUY:
			return "购买" + "<mark c=" + COLOR_NUM + ">" + m_num + "次" + "</mark>" + "额外的每日任务。" + Tools.CHANGE_ROW + "价格 ：" + "<mark c=" + COLOR_NUM + ">" + getSumMoney()
					+ "</mark>" + temp + Tools.CHANGE_ROW + "确认购买吗?";
		case STATE_TASK_IM_FIN:
			return "立即完成当前每日任务。" + Tools.CHANGE_ROW + "价格 ：" + "<mark c=" + COLOR_NUM + ">" + getSumMoney() + "</mark>" + temp + Tools.CHANGE_ROW + "确认购买吗?";
		case STATE_BUY_FUN:
			return "确认加速。";
		}
		return "加说明进去";
	}

	private byte getMoneyType() {
		return (byte) (m_is_selYinpiao ? ActorRole.YINPIAO : ActorRole.YUANBAO);
	}

	private long getMoney() {
		return m_is_selYinpiao ? m_price_yinpiao : m_price_rmb;
	}

	private void actionLeftSoftOnBuyItem() {
		GameManager.getInstance().m_game_message.sendBuyItemInMulMoney(m_item_key, getMoneyType(), getMoney(), m_num);
	}

	private void actionLeftSoftOnPresentItem() {
		GameManager.getInstance().m_game_message.sendItemToSbInMulMoney(m_item_key, getMoneyType(), getMoney(), m_num, m_id_recver, m_name_recver);
	}

	private void actionLeftSoftOnBuyFunWithMoney() {
		GameManager.getInstance().m_game_message.sendDongFuSpeedUPYUANBAO(m_dongfu_type);
		// GameManager.getInstance().m_game_message.sendBuyFunWithMoney(getMoneyType(),
		// getMoney(), m_oper_type_buy_fun);
	}

	/**
	 * 立即完成 2012-4-25 上午10:45:57 venizeng
	 */
	private void actionLeftSoftOnTaskImFin() {
		GameManager.getInstance().m_game_message.sendActivityCompleteTaskOk(getMoneyType());
	}

	/**
	 * 立即购买 2012-4-25 上午10:45:57 venizeng
	 */
	private void actionLeftSoftOnTaskImBuy() {
		GameManager.getInstance().m_game_message.sendActivityBuyTaskOk(getMoneyType());
	}

	protected void paintContent(Graphics g) {
		paintBg(g);
      switch (m_state) {
          case STATE_ITEM:
//              String toDraw = STR_BUY_YD.replace("#", m_item_name);
              paintCommon(g, null, STR_BUY_YD);//
              break;
          case STATE_ITEM_SUC:
//              String toDraw = STR_BUY_SUC.replace("#", m_item_name);
              paintCommon(g, null, STR_BUY_SUC);//
              break;
          case STATE_ITEM_FAILED:
              paintCommon(g, null,STR_BUY_FAILED);//
              break;
          case STATE_ITEM_BUYING:
              if (STR_BUYING.endsWith("...")) {
                  STR_BUYING = STR_BUYING.replace("...", ".");
              } else if (STR_BUYING.endsWith("..")) {
                  STR_BUYING = STR_BUYING.replace("..", "...");
              } else {
                  STR_BUYING = STR_BUYING.replace(".", "..");
              }
              paintCommon(g, debug_string+","+STR_BUYING, null);//
              break;
      }
//		paintCommon(g);// 公有的
//		switch (m_state) {
//		case STATE_ITEM:
//		case STATE_PRESENT:
//			paintItem(g);
//			break;
//		case STATE_TASK_IM_BUY:
//		case STATE_TASK_IM_FIN:
//		case STATE_BUY_FUN:
//			paintTask(g);
//			break;
//		}
	}

	private void paintBg(Graphics g) {
		int x = m_x;
		int y = m_y;
		UITools.drawWindowBackgroud(g, x, y, m_w, m_h);
		UITools.paintBackgroundTitleOn240320(g, x, y, m_w, m_h, m_title); // 绘制标题
		UITools.paintBackgroundButton(g, x, y, m_w, m_h, true, true);
	}

	private String STR_YONGYOU = "当前拥有";
	private String STR_SUM = "购买总价";
	private String STR_LABEL_YP = "银票";
	private String STR_LABEL_RMB = "元宝";
	private String STR_NUM = "购买数目:";
	private String SB_J="#";
	private String SB_a="@";
	private String SB_B="%";
	private String SB_7="&";
	private String[] STR_BUY_YD = new String[]{"尊敬的客户，您即将购买的商品是",
			"游戏名：无界",
	        "道具名："+SB_J,
			"道具数量：1",
	        "服务器提供商："+SB_a,
	        "客服电话:18708110382",
			"资费说明：",
			SB_B+"点（即消费"+SB_7+"元人民币）。",
	        "点击确认按钮确认购买，中国移动。"};
	private String STR_BUY_SUC[] = new String[]{"尊敬的客户，您刚刚已经成功购买",
			"道具名：#" };
	private String STR_BUY_FAILED[] = new String[]{"尊敬的客户，您刚刚购买道具" ,
			"失败，请稍后再试！" };
	private String STR_BUYING= "购买中，请稍后." ;
	private String STR_COMPANY= "四川和润文化传播有限责任公司" ;

	private void paintCommon(Graphics g, String todraw, String[] page) {
		int initX = m_x + UITools.INITX_CONTENT;
		int tempX = initX;
		int endX = m_x + m_w - UITools.IW_WIN;
		int tempY = 90;
		g.setColor(0xffffff);
		if (page != null) {
		    int size = page.length;
//		    String pageitem;
		    for(int i=0;i<size;i++) {
		        String pageitem = page[i];
//		        if (pageitem.contains("@")) {//游戏名字
//		            pageitem.replace("@", "");
//		        }
//		        else
		        if (pageitem.contains(SB_J)) {//道具名字
		            pageitem = pageitem.replace(SB_J, m_item_name);
		        }
		        else if (pageitem.contains(SB_a)) {//开发商
		            pageitem = pageitem.replace(SB_a, STR_COMPANY);
		        }
		        else if (pageitem.contains(SB_B)) {//点数
		            pageitem = pageitem.replace(SB_B, Long.toString(m_price_rmb));
		        }
		        if (pageitem.contains(SB_7)) {//人民币
		            pageitem = pageitem.replace(SB_7, Long.toString(m_price_rmb/100));
		        }
		        g.drawString(pageitem, tempX, tempY, Tools.LEFT_TOP);
		        tempY += (AbstractGameScreen.FONT_H + UITools.IH_RECTS);
		    }
		} else {
		    g.drawString(todraw, tempX, tempY, Tools.LEFT_TOP);
		}
		// 元宝数目
//		int tempY = m_y + m_h - (UITools.H_BUTTON + UITools.IW_WIN + UITools.IH_RECTS);
//		g.setColor(UIManager.getPaletteColor(UIManager.COLOR_WORD_YESS));
//		g.drawString(STR_YONGYOU, tempX, tempY, Tools.LEFT_BOTTOM);
//		UITools.paintMoneyRmbRB(g, endX, tempY, GameManager.getInstance().m_role.m_money_rmb, false);
//		// 银票数目
//		tempY -= (AbstractGameScreen.FONT_H + UITools.IH_RECTS);
//		g.setColor(UIManager.getPaletteColor(UIManager.COLOR_WORD_YESS));
//		g.drawString(STR_YONGYOU, tempX, tempY, Tools.LEFT_BOTTOM);
//		UITools.paintMoneyYinpiaoRB(g, endX, tempY, GameManager.getInstance().m_role.m_money_yinpiao, false);
//		// 购买总价
//		tempY -= (AbstractGameScreen.FONT_H + UITools.IH_RECTS);
//		g.setColor(Tools.GREEN);
//		g.drawString(STR_SUM, tempX, tempY, Tools.LEFT_BOTTOM);
//		if (m_is_selYinpiao) {
//			UITools.paintMoneyYinpiaoRB(g, endX, tempY, getSumMoney(), false);
//		} else {
//			UITools.paintMoneyRmbRB(g, endX, tempY, getSumMoney(), false);
//		}
//		// 标签（银票，元宝）
//		tempY -= ((AbstractGameScreen.FONT_H + UITools.IH_RECTS) + UITools.H_LABEL_STR);
//		int W_BUY_MONEY = (AbstractGameScreen.FONT_W << 1) + 2;// 标签的宽度
//		tempX = endX - W_BUY_MONEY - UITools.IW_RECTS;
//
//		UITools.paintLabelStr(g, tempX, tempY, W_BUY_MONEY, UITools.H_LABEL_STR, STR_LABEL_RMB, !m_is_selYinpiao);
//		if (m_index == INDEX_RMB) {
//			UITools.paintFocusBox(g, tempX, tempY, W_BUY_MONEY, UITools.H_LABEL_STR);
//		}
//		if (isSupportYinpiao()) {
//			tempX -= (W_BUY_MONEY + UITools.IW_RECTS);
//			UITools.paintLabelStr(g, tempX, tempY, W_BUY_MONEY, UITools.H_LABEL_STR, STR_LABEL_YP, m_is_selYinpiao);
//			if (m_index == INDEX_YINPIAO) {
//				UITools.paintFocusBox(g, tempX, tempY, W_BUY_MONEY, UITools.H_LABEL_STR);
//			}
//		}
//		g.setColor(Tools.GREEN);
//		g.drawString("付费货币:", initX, tempY, 0);
//
//		// 输入数目
//		tempX = initX;
//		tempY -= (UITools.H_LABEL_STR + UITools.IH_RECTS);
//		if (m_num_max > 0) {
//			g.setColor(Tools.GREEN);
//			g.drawString(STR_NUM, tempX, tempY, 0);
//			int W_NUM_INPUT = 40;
//			int H_NUM_INPUT = AbstractGameScreen.FONT_H + 4;
//			paintNumInput(g, endX - W_NUM_INPUT - 9, tempY, W_NUM_INPUT, H_NUM_INPUT, m_num);
//		}
	}
	private void paintCommon(Graphics g) {
        int initX = m_x + UITools.INITX_CONTENT;
        int tempX = initX;
        int endX = m_x + m_w - UITools.IW_WIN;
         //元宝数目
      int tempY = m_y + m_h - (UITools.H_BUTTON + UITools.IW_WIN + UITools.IH_RECTS);
      g.setColor(UIManager.getPaletteColor(UIManager.COLOR_WORD_YESS));
      g.drawString(STR_YONGYOU, tempX, tempY, Tools.LEFT_BOTTOM);
      UITools.paintMoneyRmbRB(g, endX, tempY, GameManager.getInstance().m_role.m_money_rmb, false);
      // 银票数目
      tempY -= (AbstractGameScreen.FONT_H + UITools.IH_RECTS);
      g.setColor(UIManager.getPaletteColor(UIManager.COLOR_WORD_YESS));
      g.drawString(STR_YONGYOU, tempX, tempY, Tools.LEFT_BOTTOM);
      UITools.paintMoneyYinpiaoRB(g, endX, tempY, GameManager.getInstance().m_role.m_money_yinpiao, false);
      // 购买总价
      tempY -= (AbstractGameScreen.FONT_H + UITools.IH_RECTS);
      g.setColor(Tools.GREEN);
      g.drawString(STR_SUM, tempX, tempY, Tools.LEFT_BOTTOM);
      if (m_is_selYinpiao) {
          UITools.paintMoneyYinpiaoRB(g, endX, tempY, getSumMoney(), false);
      } else {
          UITools.paintMoneyRmbRB(g, endX, tempY, getSumMoney(), false);
      }
      // 标签（银票，元宝）
      tempY -= ((AbstractGameScreen.FONT_H + UITools.IH_RECTS) + UITools.H_LABEL_STR);
      int W_BUY_MONEY = (AbstractGameScreen.FONT_W << 1) + 2;// 标签的宽度
      tempX = endX - W_BUY_MONEY - UITools.IW_RECTS;

      UITools.paintLabelStr(g, tempX, tempY, W_BUY_MONEY, UITools.H_LABEL_STR, STR_LABEL_RMB, !m_is_selYinpiao);
      if (m_index == INDEX_RMB) {
          UITools.paintFocusBox(g, tempX, tempY, W_BUY_MONEY, UITools.H_LABEL_STR);
      }
      if (isSupportYinpiao()) {
          tempX -= (W_BUY_MONEY + UITools.IW_RECTS);
          UITools.paintLabelStr(g, tempX, tempY, W_BUY_MONEY, UITools.H_LABEL_STR, STR_LABEL_YP, m_is_selYinpiao);
          if (m_index == INDEX_YINPIAO) {
              UITools.paintFocusBox(g, tempX, tempY, W_BUY_MONEY, UITools.H_LABEL_STR);
          }
      }
      g.setColor(Tools.GREEN);
      g.drawString("付费货币:", initX, tempY, 0);

      // 输入数目
      tempX = initX;
      tempY -= (UITools.H_LABEL_STR + UITools.IH_RECTS);
      if (m_num_max > 0) {
          g.setColor(Tools.GREEN);
          g.drawString(STR_NUM, tempX, tempY, 0);
          int W_NUM_INPUT = 40;
          int H_NUM_INPUT = AbstractGameScreen.FONT_H + 4;
          paintNumInput(g, endX - W_NUM_INPUT - 9, tempY, W_NUM_INPUT, H_NUM_INPUT, m_num);
      }
    }
	private void paintNumInput(Graphics g, int x, int y, int w, int h, int num) {
		int IW_NUM_ARR_RECT = 9;
		if (m_index == INDEX_NUM) {
			int[] colors = new int[] { 0x4f0000, 0x00ffea, 0x00ffea };
			for (int i = 0, length = colors.length; i < length; i++) {
				UITools.drawRect(g, x, y, w, h, colors[i], i);
			}
		} else {
			UITools.paintContentRect(g, x, y, w, h);
		}
		g.setColor(UIManager.getPaletteColor(UIManager.COLOR_WORD_YESS));
		g.drawString(String.valueOf(num), x + w - UITools.IW_RECT_CONTENT, y + UITools.IH_RECT_CONTENT, Tools.RIGHT_TOP);
		int tempY = y + ((h + UIManager.IMAGE_ARR_DARK.getWidth()) >> 1);
		Tools.drawRegion(g, UIManager.IMAGE_ARR_DARK, x - IW_NUM_ARR_RECT, tempY, Tools.TRANS_90, Tools.LEFT_BOTTOM);// 左
		Tools.drawRegion(g, UIManager.IMAGE_ARR_DARK, x + w + IW_NUM_ARR_RECT - UIManager.IMAGE_ARR_DARK.getHeight() + 1, tempY, Tools.TRANS_270, Tools.LEFT_BOTTOM);// 右
	}

	private void paintItem(Graphics g) {
		g.setColor(UIManager.getPaletteColor(UIManager.COLOR_WORD_YESS));
		g.drawString(m_item_name, m_x + (m_w >> 1), m_y + UIManager.IMAGE_TITlE_SMALL.getHeight() + UITools.IH_RECTS, Tools.HCENTER_TOP);
	}

	private int m_relY = 0;

	private void paintTask(Graphics g) {
		int tempX = m_x + UITools.INITX_CONTENT;
		int tempY = m_y + UIManager.IMAGE_TITlE_SMALL.getHeight() + UITools.IH_RECTS;
		int tempW = m_w - (UITools.INITX_CONTENT << 1);
		int tempH = (AbstractGameScreen.FONT_H << 1) + (UITools.IH_RECT_CONTENT << 1);
		int clipX = g.getClipX();
		int clipY = g.getClipY();
		int clipW = g.getClipWidth();
		int clipH = g.getClipHeight();
		UITools.paintContentRect(g, tempX, tempY, tempW, tempH);
		tempX += UITools.IW_RECT_CONTENT;
		tempY += UITools.IH_RECT_CONTENT;
		tempW -= (UITools.IW_RECT_CONTENT << 1);
		tempH -= (UITools.IH_RECT_CONTENT << 1);
		g.setClip(tempX, tempY, tempW + 1, tempH + 1);
		if (m_describe != null) {
			if (m_describe instanceof AbsHyperLinker) {
				AbsHyperLinker hyperLinker = (AbsHyperLinker) m_describe;
				hyperLinker.paintInRect(g, tempX, tempY - m_relY);
			} else {
				String[] temps = null;
				try {
					temps = (String[]) m_describe;

				} catch (Exception e) {

				}
				if (temps != null) {
					g.setColor(UIManager.getPaletteColor(UIManager.COLOR_WORD_NOS));
					for (int i = 0; i < temps.length; i++) {
						if (temps[i] == null) {
							continue;
						}
						g.drawString(temps[i], tempX, tempY, 0);
						tempY += AbstractGameScreen.FONT_H;
					}
				}
			}

		}
		int H = m_h_descrbei - tempH;
		if (H > 0) {
			m_relY++;
			if (m_relY >= m_h_descrbei) {
				m_relY = 0;
			}
		}
		g.setClip(clipX, clipY, clipW, clipH);
	}

}
